const path = require('path');

const express = require('express');

const errorController = require('./controllers/error');
const sequelize = require('./utils/database');
const Product = require('./modules/product');
const User = require('./modules/user');
const Cart = require('./modules/cart');
const CartItem = require('./modules/cart-item');
const Order = require('./modules/order');
const OrderItem = require('./modules/order-item');

const app = express();

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
    User.findByPk(1)
    .then(user => {
        req.user = user;
        next();
    })
    .catch(err => console.log(err))
})

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.use('/', errorController.get404);

Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
User.hasOne(Cart);
Cart.belongsTo(User);
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
User.hasMany(Order);
Order.belongsTo(User);
Order.belongsToMany(Product, { through: OrderItem });
Product.belongsToMany(Order, { through: OrderItem });

let currentUser;
sequelize
// .sync({ force: true })
.sync()
.then(() => {
    return User.findByPk(1);
})
.then(user => {
    if (user) {
        return user;
    } else {
        return User.create({ name: 'tina', email: 'mysql@db.com' });
    }
})
.then(user => {
    currentUser = user;
    return user.getCart();
})
.then(cart => {
    if (cart) {
        return cart;
    } else {
        return currentUser.createCart();
    }
})
.then(cart => {
    app.listen(443);
})
.catch(err => console.log(err))